import django_filters
from django.db.models import Q

from app.autojob.models import InitTaskList, OSInstallTaskList
from init_task import value


class InitTaskListFilter(django_filters.FilterSet):
    """设备类出库过滤器"""
    systemSN = django_filters.CharFilter(field_name='systemSN', lookup_expr='exact')
    ticketSn = django_filters.CharFilter(field_name='ticketSn', lookup_expr='exact')
    businessIp = django_filters.CharFilter(field_name='businessIp', lookup_expr='exact')
    idc = django_filters.CharFilter(field_name='idc', lookup_expr='exact')
    status = django_filters.CharFilter(method='multi_filter')
    is_deleted = django_filters.CharFilter(field_name='is_deleted', lookup_expr='exact')

    class Meta:
        model = InitTaskList
        fields = ['systemSN', 'ticketSn', 'businessIp', 'idc', 'is_deleted']

    def multi_filter(self, queryset, name, value):
       values = value.strip().split(',') if value else []

       q_objects = Q()
       for val in values:
           q_objects |= Q(**{f"{name}__exact": val})

       return queryset.filter(q_objects)


class OSInstallTaskListFilter(django_filters.FilterSet):
    """设备类出库过滤器"""
    systemSN = django_filters.CharFilter(field_name='systemSN', lookup_expr='exact')
    ticketSn = django_filters.CharFilter(field_name='ticketSn', lookup_expr='exact')
    businessIp = django_filters.CharFilter(field_name='businessIp',lookup_expr='exact')
    idc = django_filters.CharFilter(field_name='idc',lookup_expr='exact')
    status = django_filters.CharFilter(method='multi_filter')
    is_deleted = django_filters.CharFilter(field_name='is_deleted', lookup_expr='exact')
    netEnv = django_filters.CharFilter(field_name='netEnv', lookup_expr='exact')

    class Meta:
        model = OSInstallTaskList
        fields = ['systemSN', 'ticketSn', 'businessIp', 'idc', 'status', 'is_deleted', 'netENV']

    def multi_filter(self, queryset, name, value):
        values = value.strip().split(',') if value else []

        # 使用 Q 对象来处理字符串和列表筛选
        q_objects = Q()
        for val in values:
            q_objects |= Q(**{f"{name}__exact": val})

        return queryset.filter(q_objects)
